<template>
  <div class="class-mana">
    <q-form class="toolbar form-inline items-center">
      <q-select
        class="select"
        outlined dense emit-value map-options options-dense
        :options="workshopOpt"
        :loading="plantLoading"
        v-model="plant"
        @input="getShiftsList"
      >
        <template v-slot:before>
          <span class="form-name">车间:</span>
        </template>
        <template v-slot:append>
          <q-icon name="close" v-if="plant!==null" @click.stop="clearPlant"
                  class="cursor-pointer" />
        </template>
      </q-select>
      <div class="font-14 text-grey flex-1 padding-l-20">*班制变更后，自动打回功能将关闭</div>
      <q-btn @click="addShiftDialog('add')" class="btn" outline type="submit" color="primary"
             label="添加班制" />
    </q-form>
    <q-table
      :data="data" :columns="columns" :loading="dataLoading"
      row-key="id" class="myTable myTable-1 shifts-table td-item td-item-min padding-r-20 padding-l-20"
      :pagination="{ rowsPerPage: 0 }" :hide-bottom="!!data.length" square @request="getShiftsList">
      <template v-slot:body="props">
        <q-tr :props="props" class="bordered-tr">
          <q-td key="workShopName" :props="props" class="bordered-td">{{ props.row.workShopName }}
          </q-td>
          <q-td key="modeName" :props="props" class="bordered-td">{{ props.row.modeName }}</q-td>
          <q-td key="enable" :props="props" class="bordered-td">
            <q-toggle
              :true-value="statusToggleTrueVal"
              :false-value="statusToggleFalseVal"
              :disable="isStatusToggleDisabled[props.row.id] || props.row.enable === statusToggleTrueVal"
              @input="enable(props.row, $event)"
              v-model="props.row.enable"
            />
          </q-td>
          <q-td key="name" :props="props" class="bordered-td shifts-wrapper">
            <dl class="shifts-box">
              <dd
                class="shifts-info td-item td-item-min"
                v-for="(shift, index) in props.row.list"
                :key="shift.id"
              >
                {{ props.row.list[index].name }}
              </dd>
            </dl>
          </q-td>
          <q-td key="time" :props="props" class="bordered-td shifts-wrapper">
            <dl class="shifts-box">
              <dd
                class="shifts-info td-item td-item-min"
                :class="{ highlight: seleRow.id && seleRow.id === shift.id }"
                v-for="(shift, index) in props.row.list"
                :key="shift.id"
              >
                <q-btn @click.native="selcShift(props.row.list[index], props.row.workShopName)" flat dense color="primary">
                  <span v-show="props.row.list[index].isStartTimeCross">次</span>{{props.row.list[index].startTime}} - <span v-show="props.row.list[index].isEndTimeCross">次</span>{{props.row.list[index].endTime}}
                </q-btn>
              </dd>
            </dl>
          </q-td>
          <q-td key="comments" :props="props" class="bordered-td">{{ props.row.comments ?  props.row.comments : '--' }}</q-td>
          <q-td key="operations" :props="props" class="bordered-td">
            <table-btn btnType="edit" @click="editShiftDialog(props.row)"/>
            <table-btn btnType="delete" :disabled="props.row.enable" @click="delDialog(props.row)" tips="确定要删除此项吗？"/>
          </q-td>
        </q-tr>
      </template>
    </q-table>

    <div class="detail padding-t-20">
<!--      <q-separator class="line" />-->
      <div class="title row no-wrap items-center no-border-radius">
        <q-icon name="iconfont icontubiao-41" class="margin-l-20"></q-icon>
        <span class="title-name font-size-14 text-weight-bold">轮班时间明细</span>
<!--        <q-space />-->
<!--        <q-icon-->
<!--          class="cursor-pointer"-->
<!--          :disabled="seleRow === null"-->
<!--          @click="openShiftitemDialog('add')"-->
<!--          name="iconfont icontubiao-50">-->
<!--          <q-tooltip>添加</q-tooltip>-->
<!--        </q-icon>-->
      </div>
      <q-table :data="dataTime" :columns="columnTime"
               row-key="name" class="myTable myTable-2 scroll margin-l-20 margin-r-20"
               :loading="dataTimeLoading"
               :pagination="{rowsPerPage: 0}" :hide-bottom="!!dataTime.length">
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="time" :props="props">
              {{ props.row.startTime }} - {{ props.row.endTime }}
            </q-td>
            <q-td key="iswork" :props="props">
            <span class="text">
              {{ props.row.workFlag === 1 ? '是' : '否' }}
            </span>
            </q-td>
            <q-td key="description" :props="props">{{ props.row.description ? props.row.description : '--'}}</q-td>
            <q-td key="operations" :props="props">
              <table-btn btnType="other" icon="icontubiao-39" tooltip="添加" @click="openShiftitemDialog('add', props.row)" v-if="props.row.workFlag === 1"/>
              <table-btn btnType="edit" @click="openShiftitemDialog('edit', props.row)" v-if="props.row.workFlag === 0"/>
              <table-btn btnType="delete" v-if="props.row.workFlag === 0" @click="delShiftitemDialog(props.row)" tips="确定要删除此项吗？"/>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>

    <!--新增编辑班制对话框-->
    <add-edit-shift-dialog-new
      ref="addEditShift"
      :workshopOpt="workshopOpt"
      :show="addEditShiftDialogNew.show"
      :state="addEditShiftDialogNew.state"
      @submit="_submit"
      @close="addEditShiftDialogNew.show = false"
    />

    <!--新增编辑班制时间对话框-->
    <add-edit-shiftitem-dialog
      ref="shiftitemDialog"
      :workShopName="workShopName"
      @submit="submitShiftitem"/>

  </div>
</template>

<script>
import {
  addShiftItem,
  addShifts,
  changeEnable,
  delShiftItem,
  delShifts,
  editShiftItem,
  editShifts,
  getShiftByWorkshop,
  getShiftItems
} from 'src/boot/factory/factory-calendar'
import { getWorkshops } from 'src/boot/common/dict'
import AddEditShiftitemDialog from './components/add-edit-shiftitem-dialog'
// 业务更改后的新增编辑班制对话框
import AddEditShiftDialogNew from './components/add-edit-shift-dialog-new'

export default {
  name: 'class-mana',
  components: {
    AddEditShiftitemDialog,
    AddEditShiftDialogNew
  },
  data () {
    return {
      workshopOpt: [],
      statusToggleTrueVal: true, // 状态 toggle 为 true 时的 status 值
      statusToggleFalseVal: false, // 状态 toggle 为 false 时的 status 值
      addEditShiftDialogNew: {
        show: false,
        state: '',
        workshopOpt: []
      }, // 新增编辑班制对话框参数
      isStatusToggleDisabled: {}, // 避免用户操作过快
      plant: null, // 选中的厂区
      data: [], // 班制管理数据
      dataLoading: false, // 班制管理数据加载状态
      seleRow: null, // 选中的数据
      dataTime: [], // 班制时间设置
      dataTimeLoading: false, // 班制时间设置加载状态
      // 班制管理表头数据
      columns: [
        { name: 'workShopName', field: 'workShopName', label: '车间', align: 'left' },
        { name: 'modeName', field: 'modeName', label: '班制模式', align: 'left' },
        { name: 'enable', field: 'enable', label: '是否启用', align: 'left' },
        { name: 'name', field: 'name', label: '轮班名称', align: 'left' },
        { name: 'time', field: 'time', label: '轮班时间', align: 'left' },
        { name: 'comments', field: 'comments', label: '备注', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      // 班制管理表头数据
      columnTime: [
        { name: 'time', field: 'time', label: '时间段', align: 'left' },
        { name: 'iswork', field: 'iswork', label: '是否工作', align: 'left' },
        { name: 'description', field: 'description', label: '说明', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      workShopName: '' // 选中的车间
    }
  },
  computed: {
    // useData () {
    //   const info = []
    //   for (let i = 0; i < this.data.length; i++) {
    //     for (let j = 0; j < this.data[i].teamList.length; j++) {
    //       let item = {
    //         ...this.data[i],
    //         ...this.data[i].teamList[j],
    //         rowSpan: j === 0 ? this.data[i].teamList.length : 0,
    //         isEven: !(i % 2)
    //       }
    //       delete item.teamList
    //       info.push(item)
    //     }
    //   }
    //   return info
    // }
  },
  created () {
    this.getWorkshopList()
    this.getShiftsList()
  },
  methods: {

    // 获取车间列表
    getWorkshopList () {
      this.plantLoading = true
      getWorkshops(null).then(res => {
        let workshopOpt = [{
          label: '全部',
          value: null
        }]
        this.workshopOpt = workshopOpt.concat(res.data)
        this.plantLoading = false
      })
    },

    // 获取班制列表
    getShiftsList () {
      const params = {
        id: this.plant
      }
      this.dataLoading = true
      getShiftByWorkshop(params).then((res) => {
        // res.data.forEach(o => {
        //   o.highlight = false
        // })
        for (const i of res.data) {
          for (const j of i['list']) {
            j['highlight'] = false
          }
        }
        this.data = this.initShiftsList(res.data)
        if (res.data.length > 0) {
          this.workShopName = this.data[0].workShopName
          if (res.data[0].list.length) {
            this.seleRow = this.data[0].list[0]
            this.getShiftItemList(this.seleRow.id)
          }
        } else {
          this.seleRow = null
          this.dataTime = []
        }
      }).finally(() => {
        this.dataLoading = false
      })
    },
    initShiftsList (list) {
      return list.map(item => {
        item.list = item.list.map(child => {
          let endTimeArr = child.endTime.split(':')
          let startTimeArr = child.startTime.split(':')
          return {
            ...child,
            startTime: startTimeArr[0] + ':' + startTimeArr[1],
            endTime: endTimeArr[0] + ':' + endTimeArr[1]
          }
        })
        return item
      })
    },

    // 切换班制禁用/启用状态
    enable: function (val, status) {
      const _that = this
      this.$utils.showMessage('icontubiao-28', '切换班制该车间启用的保养计划将被禁用', () => {
        _that.$set(_that.isStatusToggleDisabled, val.id, true)
        changeEnable(val.id, status).then(() => {
          _that.getShiftsList()
        }).catch(() => {
          val.enable = !val.enable
        }).finally(() => {
          _that.$set(_that.isStatusToggleDisabled, val.id, false)
        })
      }, true, () => {
        val.enable = !val.enable
        _that.$set(_that.isStatusToggleDisabled, val.id, false)
      })
    },

    // 清空厂区
    clearPlant () {
      this.plant = null
      this.getShiftsList()
    },

    // 点击添加班制
    addShiftDialog (state = 'add', item) {
      // this.$refs.shiftDialog.showDialog(state, item, this.plant)
      this.addEditShiftDialogNew.show = true
      this.addEditShiftDialogNew.state = 'add'
      this.$refs.addEditShift.reset()
    },

    // 点击编辑班制
    editShiftDialog (val) {
      this.addEditShiftDialogNew.show = true
      this.addEditShiftDialogNew.state = 'edit'
      this.$refs.addEditShift.assignment(val)
    },

    // 提交新增或编辑班制
    _submit (state, form) {
      const query = {
        shifts: []
      }
      // query.id = state === 'add' ? undefined : form.id
      query.comments = form.comments
      query.modeCode = form.classMode
      query.workShopId = form.workshop
      if (form.classMode >= 1) {
        query.shifts.push({
          id: state === 'add' ? undefined : form.shiftId1,
          name: form.shiftName1,
          startTime: this.timeToDateString(form.startTime1, form.nextStart1),
          endTime: this.timeToDateString(form.endTime1, form.nextEnd1),
          isStartTimeCross: form.nextStart1,
          isEndTimeCross: form.nextEnd1
        })
      }
      if (form.classMode >= 2) {
        query.shifts.push({
          id: state === 'add' ? undefined : form.shiftId2,
          name: form.shiftName2,
          startTime: this.timeToDateString(form.startTime2, form.nextStart2),
          endTime: this.timeToDateString(form.endTime2, form.nextEnd2),
          isStartTimeCross: form.nextStart2,
          isEndTimeCross: form.nextEnd2
        })
      }
      if (form.classMode >= 3) {
        query.shifts.push({
          id: state === 'add' ? undefined : form.shiftId3,
          name: form.shiftName3,
          startTime: this.timeToDateString(form.startTime3, form.nextStart3),
          endTime: this.timeToDateString(form.endTime3, form.nextEnd3),
          isStartTimeCross: form.nextStart3,
          isEndTimeCross: form.nextEnd3
        })
      }
      if (form.classMode >= 4) {
        query.shifts.push({
          id: state === 'add' ? undefined : form.shiftId4,
          name: form.shiftName4,
          startTime: this.timeToDateString(form.startTime4, form.nextStart4),
          endTime: this.timeToDateString(form.endTime4, form.nextEnd4),
          isStartTimeCross: form.nextStart4,
          isEndTimeCross: form.nextEnd4
        })
      }
      // 校验必填
      const flag = this.judge(form)
      if (flag) {
        if (state === 'add') {
          addShifts(query).then(() => {
            this.getShiftsList()
            this.$message.success('添加成功')
            this.addEditShiftDialogNew.show = false
          })
        } else {
          editShifts(query, form.id).then(() => {
            this.getShiftsList()
            this.$message.success('修改成功')
            this.addEditShiftDialogNew.show = false
          })
        }
      }
    },

    // 删除班制弹框
    delDialog (item) {
      delShifts(item.id).then(() => {
        this.$message.success('删除成功')
        this.getShiftsList()
      })
    },

    // 选中班制
    selcShift (item, workShopName, shift) {
      this.seleRow = item
      this.getShiftItemList(item.id)
      this.workShopName = workShopName
    },

    // 获取班制时间列表
    getShiftItemList (id) {
      this.dataTimeLoading = true
      getShiftItems(id).then((res) => {
        this.dataTime = this.initShiftItem(res.data)
      }).finally(() => {
        this.dataTimeLoading = false
      })
    },
    // 初始化班制时间列表
    initShiftItem (data) {
      return data.map((item, index) => {
        let endTimeArr = item.endTime.split(':')
        let startTimeArr = item.startTime.split(':')
        return {
          ...item,
          index,
          startTime: startTimeArr[0] + ':' + startTimeArr[1],
          endTime: endTimeArr[0] + ':' + endTimeArr[1]
        }
      })
    },

    // 打开新增编辑班制时间对话框
    openShiftitemDialog (state = 'add', item) {
      // 工作时段
      let workTime = {
        startTime: state === 'add' ? item.startTime : this.dataTime[item.index - 1].startTime,
        endTime: state === 'add' ? item.endTime : this.dataTime[item.index + 1].endTime
      }
      this.$refs.shiftitemDialog.showDialog(state, item, this.seleRow, workTime)
    },

    // 提交班制时间
    submitShiftitem (state, params, id) {
      if (state === 'add') {
        addShiftItem(params, this.seleRow.id, this.seleRow.shiftsModeId).then((res) => {
          this.getShiftItemList(this.seleRow.id)
          this.$refs.shiftitemDialog.hideDialog()
          this.$message.success('添加成功')
        }).finally(() => {
          this.$refs.shiftitemDialog.submitting = false
        })
      } else {
        editShiftItem(params, id, this.seleRow.shiftsModeId).then((res) => {
          this.getShiftItemList(this.seleRow.id)
          this.$refs.shiftitemDialog.hideDialog()
          this.$message.success('修改成功')
        }).finally(() => {
          this.$refs.shiftitemDialog.submitting = false
        })
      }
    },

    // 删除班制时间弹框
    delShiftitemDialog (item) {
      delShiftItem(item.id, this.seleRow.shiftsModeId).then(() => {
        this.$message.success('删除成功')
        this.getShiftItemList(this.seleRow.id)
      })
    },

    // 判断提交的班制数据是否合法
    judge (form) {
      let flag = false
      if (form.classMode === '1') {
        if (form.shiftName1 === '' || form.startTime1 === '' || form.endTime1 === '') {
          this.$message.warning('数据不允许为空')
          flag = false
        } else {
          flag = true
        }
      } else if (form.classMode === '2') {
        if (form.shiftName1 === '' || form.startTime1 === '' || form.endTime1 === '' ||
          form.shiftName2 === '' || form.startTime2 === '' || form.endTime2 === '') {
          this.$message.warning('数据不允许为空')
          flag = false
        } else {
          flag = true
        }
      } else if (form.classMode === '3') {
        if (form.shiftName1 === '' || form.startTime1 === '' || form.endTime1 === '' ||
          form.shiftName2 === '' || form.startTime2 === '' || form.endTime2 === '' ||
          form.shiftName3 === '' || form.startTime3 === '' || form.endTime3 === '') {
          this.$message.warning('数据不允许为空')
          flag = false
        } else {
          flag = true
        }
      } else {
        if (form.shiftName1 === '' || form.startTime1 === '' || form.endTime1 === '' ||
          form.shiftName2 === '' || form.startTime2 === '' || form.endTime2 === '' ||
          form.shiftName3 === '' || form.startTime3 === '' || form.endTime3 === '' ||
          form.shiftName4 === '' || form.startTime4 === '' || form.endTime4 === '') {
          this.$message.warning('数据不允许为空')
          flag = false
        } else {
          flag = true
        }
      }
      return flag
    },
    // 由时间转化为日期字符串
    timeToDateString (time, isNext) {
      const preifx = '1970-02-01T'
      const preifx1 = '1970-02-02T'
      const suffix = '.224Z'

      const datetimeStr = isNext ? `${preifx1}${time}:00${suffix}` : `${preifx}${time}:00${suffix}`
      return datetimeStr
    }
  }
}
</script>

<style scoped lang="stylus">
  .class-mana{
    display flex
    flex-direction column
    .form-inline {
      flex 52px 0
    }
  }

  .myTable-1 {
    margin 0
    max-height calc(100% - 52px)
    min-height calc(50% - 52px)

    .active-tr {
      td {
        background-color rgba(159, 173, 254, 0.6)
      }
    }

    th {
      border-right 1px solid rgba(211, 211, 211, 1)
      border-bottom 1px solid rgba(211, 211, 211, 1)

      &:last-child {
        border-right none
      }
    }

    tbody tr {
      &:hover {
        background-color transparent
      }

      td {
        border-right 1px solid rgba(211, 211, 211, 1)
        border-bottom 1px solid rgba(211, 211, 211, 1)
      }

      td:last-child {
        border-right none
      }
    }

    tbody tr.even-tr {
      background-color #f9f9f9

      &:hover {
        background-color #f9f9f9
      }
    }

    &::-webkit-scrollbar {
      width 6px
      height 6px
      background-color transparent
    }

    &::-webkit-scrollbar-thumb {
      border-radius 6px
      background-color rgba(95, 119, 253, 0)
      transition background-color 500ms ease-in
    }

    &::-webkit-scrollbar-thumb {
      background-color rgba(95, 119, 253, .5)
    }

    &::-webkit-scrollbar-track {
      margin-left -6px
      padding-top 48px
      background-color transparent
      width 0
    }
  }
  .detail{
    max-height 50%
    min-height 30%
  }
  .myTable-2 {
    height calc(100% - 69px)
  }

  .line {
    margin 15px 0
  }

  .title {
    margin 0 0 20px
    padding 9px 15px
    background-color $primary
    color #fff
    font-size 20px
    border-radius: 6px 6px 0px 0px

    .title-name {
      margin 0 30px 0 10px
    }
  }

  .shifts-table {
    $border-style = 1px solid #D3D3D3
    flex 1
    /*border-top $border-style*/
    border-radius 6px
    overflow hidden

    /deep/ th:not(:last-child) {
      border-right $border-style
    }

    /deep/ .q-table {
      border-left $border-style
      border-right $border-style
    }

    .bordered-tr {
      &:not(:last-child) td {
        border-bottom $border-style
      }

      &:last-child {
        .bordered-td {
          border-bottom none
        }
      }

      &:hover, &:hover td {
        background none !important

        &:before {
          background none
        }
      }

      &:nth-child(even):hover {
        background-color #F9F9F9 !important
      }

      .bordered-td {
        &:not(:last-child) {
          border-right $border-style
        }

        &.shifts-wrapper {
          padding 0

          .shifts-box {
            margin 0

            .shifts-info {
              margin 0
              height 48px
              display flex
              align-items center
              justify-content space-between
              padding 0 20px 0 20px
              position relative

              &:not(:last-child) {
                border-bottom $border-style
              }

              &.highlight {
                background-color #CFD6FE
              }
            }
          }
        }
      }
    }
  }
  >>>.td-item-min{
    padding-top 0
    padding-bottom 0
  }
</style>
<style lang="stylus">
  .shifts-table{
    .q-table__middle{
      border 1px solid #D3D3D3
      border-left 0
    }
  }
</style>
